<template>
  <transition>
    <div v-if="visible" class="detail-main">
      <el-page-header @back="handleClose" :icon="null" class="detail-header">
        <template #title>
          <div class="detail-header-title">
            {{props.id ? '编辑' : '新增'}}
          </div>
        </template>
        <template #content>
          角色信息
        </template>
        <template #extra>
          <div style="flex: auto">
            <el-button type="primary" @click="handleOk(formRef)" :loading="state.subLoading" :icon="Select">
              保存
            </el-button>
            <el-button @click="handleClose" :icon="Back">返回列表</el-button>
          </div>
        </template>
      </el-page-header>
      <div class="detail-form">
        <el-form ref="formRef" :model="formState" :rules="rules" v-loading="state.subLoading" label-width="auto">
          <el-row :gutter="20">
            <el-col :span="10" :offset="1">
              <div class="detail-from-title">
                <h2>基本信息</h2>
              </div>
              <el-form-item prop="name" label="角色名称">
                <el-input id="name" v-model="formState.name" placeholder="请输入角色名称"  class="w-500" clearable />
              </el-form-item>
              <el-form-item label="角色描述">
                <el-input type="textarea" v-model.trim="formState.description" row="2" class="w-500" />
              </el-form-item>
            </el-col>
            <el-col :span="10" :offset="1">
              <div class="detail-from-title">
                <h2>角色授权</h2>
              </div>
              <el-tree
                  ref="treeRef"
                  show-checkbox
                  :data="state.menus"
                  node-key="id"
                  :default-checked-keys="state.checkedKeys"
                  :props="defaultProps"
              />
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
  </transition>
</template>

<script setup name="RoleDetail">
import {RoleApi} from '@/api/system/role';
import useCurrentInstance from '@/hooks/useCurrentInstance';
import { Back, Select } from '@element-plus/icons-vue'
import { detailState, state, setSubLoading, rules } from '@/views/system/role/index'

const {proxy} = useCurrentInstance();
const emits = defineEmits(["refreshData"]);
let formState = toRef(detailState);
const formRef = ref();
const treeRef = ref();
const visible = ref(false)
const props = defineProps({
  id: {
    type: [String],
    required: false,
  },
  drawer: {
    type: Boolean,
    required: true,
  }
});
const defaultProps = {
  children: 'children',
  label: 'name',
}
function handleOk(formEl) {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      setSubLoading(true);
      formState.value.menuIds = treeRef.value.getCheckedKeys(false);
      if (formState.value.id) {
        RoleApi.update(formState.value).then(res => {
          if (res.success) {
            proxy.$message.success(res.message);
            handleClose();
          } else {
            proxy.$message.error(res.message);
          }
        });
      } else {
        RoleApi.save(formState.value).then(res => {
          if (res.success) {
            proxy.$message.success(res.message);
            handleClose();
          } else {
            proxy.$message.error(res.message);
          }
        });
      }
      setSubLoading(false);
    } else {
      console.log('error submit!', fields)
    }
  })

}

//关闭弹窗
function handleClose() {
  formRef.value?.resetFields()
  emits('refreshData');
  resetData();
}

//查询菜单树形结构
function findRoleTree(id) {
  const res = RoleApi.findRoleTree({id});
  if (res.success && res.data) {
    state.menus = res.data;
    findCheckedKeys(res.data)
  }
  return res;
}

//筛选已选中的菜单
function findCheckedKeys(data) {
  proxy._.forEach(data, (o) => {
    if (o.checked && o.children.length === 0) {
      state.checkedKeys.push(o.id)
    }
    if (o.checked && o.children && o.children.length > 0) {
      findCheckedKeys(o.children)
    }
  })
}

//初始化数据
function initInfo(id) {
  setSubLoading(true);
  findRoleTree(id).then((res) => {
    if (res.success && id) {
      RoleApi.findById({id}).then((res) => {
        if (res && res.success) {
          formState.value = res.data;
        }
      }).catch((error) => {
        console.log(error);
      })
    }
  }).catch((error) => {
    console.log(error);
  }).finally(() => {
    setSubLoading(false);
  })
}

//重置数据
function resetData() {
  formState.value = detailState;
  state.checkedKeys = [];
}

//监听props.visible 值得变化
watch(() => props.drawer, v => {
  visible.value = v
})
defineExpose({
  initInfo,
})

</script>

<style scoped lang="scss">
.el-card {
  border: none !important;
  box-shadow: none !important; /* 如果你也想去掉阴影，可以加上这一行 */
}
</style>
